<template>
  <a-drawer width="35%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules">
      <a-form-model-item label="字段显示名称" prop="name">
        <a-input v-model="form.name" placeholder="请输入字段显示名称，不允许重复" />
      </a-form-model-item>
      <a-form-model-item label="字段标识" prop="code">
        <a-input v-model="form.code" placeholder="请输入字段名，请使用下划线方式命名" />
      </a-form-model-item>
      <a-form-model-item label="数据类型" prop="htmlType">
        <a-select v-model="form.htmlType" style="width:100%">
          <a-select-option value="input">文本框</a-select-option>
          <a-select-option value="textarea">文本域</a-select-option>
          <a-select-option value="select">下拉框</a-select-option>
          <a-select-option value="radio">单选框</a-select-option>
          <a-select-option value="checkbox">复选框</a-select-option>
          <a-select-option value="date">日期</a-select-option>
          <a-select-option value="image">图片</a-select-option>
          <a-select-option value="file">文件</a-select-option>
          <a-select-option value="editor">富文本</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="字符限制(-1为不限制)" prop="maxLength" v-show="['input', 'textarea'].includes(form.htmlType)">
        <a-input-number v-model="form.maxLength" :min="-1" :max="500" style="width: 100%"/>
      </a-form-model-item>
      <a-form-model-item label="字典" prop="dictId" v-show="['select', 'radio', 'checkbox'].includes(form.htmlType)">
        <a-select v-model="form.dictId">
          <a-select-option
            v-for="item in dictOptions"
            :key="item.dictType"
            :value="item.dictType">
            {{ item.dictName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="在列表页中显示" prop="listShow">
        <a-radio-group v-model="form.listShow" button-style="solid">
          <a-radio-button value="0" >显示</a-radio-button>
          <a-radio-button value="1" >隐藏</a-radio-button>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="关联表" prop="linkTable">
        <a-cascader
          :options="linkTables"
          :load-data="loadLinkColumns"
          placeholder="可选择关联表以及显示字段"
          expand-trigger="hover"
          @change="onLinkChange"
        />
      </a-form-model-item>
      <a-form-model-item label="备注" prop="remark">
        <a-input v-model="form.remark" placeholder="请输入" type="textarea" allow-clear :maxLength="200" />
      </a-form-model-item>
      <div class="bottom-control">
        <a-space>
          <a-button type="primary" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>

import { listTable } from '@/api/free/table'
import { listColumn, addColumn, updateColumn } from '@/api/free/column'
import { optionSelect as getDictTypeAll } from '@/api/system/dict/type'

export default {
  name: 'CreateForm',
  props: {
    tableName: {
      type: String,
      required: true
    }
  },
  components: {
  },
  data () {
    return {
      loading: false,
      formTitle: '',
      // 所有字典
      dictOptions: [],
      // 表单参数
      form: {
        code: undefined,
        name: undefined,
        tableName: this.tableName,
        htmlType: 'input',
        maxLength: 50,
        dictId: '',
        listShow: '0',
        remark: ''
      },
      oldHtmlType: undefined,
      oldMaxLength: undefined,
      open: false,
      rules: {
        code: [{ required: true, message: '字段标识不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '字段显示不能为空', trigger: 'blur' }]
      },
      // 关联表选项
      linkTables: []
    }
  },
  filters: {
  },
  created () {
  },
  watch: {
  },
  methods: {
    onClose () {
      this.open = false
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        code: undefined,
        name: undefined,
        tableName: this.tableName,
        htmlType: 'input',
        maxLength: 50,
        dictId: '',
        listShow: '0',
        remark: ''
      }
    },
     /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.formTitle = '添加字段'
      this.loadDictList()
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      this.form = row
      this.open = true
      this.formTitle = '修改字段'
      this.loadDictList()
    },
    loadDictList () {
      getDictTypeAll().then(response => {
        this.dictOptions = response
      })
      listTable().then(response => {
        this.linkTables = response.map(item => {
          return {
            label: item.tableLabel,
            value: item.tableName,
            isLeaf: false
          }
        })
      })
    },
    loadLinkColumns (selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true

      listColumn({ tableName: targetOption.value }).then(response => {
        targetOption.children = (response || []).map(item => {
          return {
            label: item.name,
            value: item.code
          }
        })
        targetOption.loading = false
        this.linkTables = [...this.linkTables]
      })

    },
    onLinkChange(value) {
      this.form.linkTable = value.join('.')
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.columnType = this.getColumnType()
          if (this.formTitle.includes('修改')) {
            updateColumn(this.form).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.open = false
              this.$emit('ok', response)
            })
          } else {
            addColumn(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok', response)
            })
          }
        } else {
          return false
        }
      })
    },
    getColumnType() {
      const { maxLength } = this.form
      if (maxLength === -1) {
        return 'text'
      }
      switch (this.form.htmlType) {
        case 'input':
        case 'textarea':
          return `varchar(${maxLength})`
        case 'date':
          return 'date'
        case 'image':
        case 'file':
          return 'varchar(255)'
        case 'editor':
          return 'text'
      }
      return 'varchar(50)'
    }
  }
}
</script>
